package com.lxp.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxp.order.client.CourseFrontClient;
import com.lxp.order.client.UCenterMemberClient;
import com.lxp.order.domain.TOrder;
import com.lxp.order.mapper.TOrderMapper;
import com.lxp.order.service.TOrderService;
import com.lxp.order.utils.OrderNoUtil;
import com.lxp.utils.JwtUtils;
import com.lxp.utils.vo.orderVo.CourseFrontOrderVo;
import com.lxp.utils.vo.orderVo.UCenterOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author lxp
 * @since 2022-02-03
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Autowired
    private CourseFrontClient courseFrontClient;
    @Autowired
    private UCenterMemberClient centerMemberClient;
    //生成订单
    @Override
    public String createOrder(HttpServletRequest request, String courseId) {
        //利用NaCos调用服务进行信息采集
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        //获取用户信息
        UCenterOrderVo user = centerMemberClient.getUser(userId);
        //获取课程详情信息
        CourseFrontOrderVo courseInfo = courseFrontClient.getClientCourseInfo(courseId);
        TOrder tOrder =new TOrder();
        tOrder.setOrderNo(OrderNoUtil.getOrderNo());
        tOrder.setCourseId(courseInfo.getId());
        tOrder.setCourseTitle(courseInfo.getTitle());
        tOrder.setCourseCover(courseInfo.getCover());
        tOrder.setTeacherName(courseInfo.getTeacherName());
        tOrder.setPrice(courseInfo.getPrice());
        tOrder.setMemberId(user.getId());
        tOrder.setNickname(user.getNickname());
        tOrder.setEmail(user.getEmail());
        baseMapper.insert(tOrder);
        return tOrder.getOrderNo();
    }


    //检查用户是否购买了该课程
    @Override
    public boolean checkUserIsBuy(HttpServletRequest request, String courseId) {
        //获取用户id
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        Integer count = baseMapper.selectCount(new QueryWrapper<TOrder>()
                .eq("course_id", courseId)
                .eq("member_id", userId)
                .eq("status", 1));
        return count>0;
    }
}
